#!/bin/bash

# 设置变量
PROJECT_NAME="hello_blog1"
JAR_FILE="target/hello_blog1-0.0.1-SNAPSHOT.jar"
IMAGE_NAME="$PROJECT_NAME:latest"
CONTAINER_NAME="$PROJECT_NAME"

# 远程服务器配置（请根据实际情况修改）
REMOTE_SERVER="121.40.126.4"
REMOTE_USER="root"
SSH_KEY_PATH="$HOME/.ssh/id_rsa"  # SSH 密钥路径
REMOTE_DEPLOY_PATH="/opt/$PROJECT_NAME"

# 构建 Docker 镜像
echo "Building Docker image..."
docker build -t $IMAGE_NAME .

# 保存 Docker 镜像为 tar 文件
echo "Saving Docker image to tar file..."
docker save $IMAGE_NAME | gzip > $PROJECT_NAME.tar.gz

# 在远程服务器上创建部署目录
echo "Creating deployment directory on remote server..."
ssh -i $SSH_KEY_PATH -o StrictHostKeyChecking=no $REMOTE_USER@$REMOTE_SERVER "mkdir -p $REMOTE_DEPLOY_PATH"

# 复制 Docker 镜像和部署脚本到远程服务器
echo "Copying Docker image to remote server..."
scp -i $SSH_KEY_PATH -o StrictHostKeyChecking=no $PROJECT_NAME.tar.gz $REMOTE_USER@$REMOTE_SERVER:$REMOTE_DEPLOY_PATH/

echo "Copying deployment script to remote server..."
cat > remote_deploy.sh << 'EOF'
#!/bin/bash

PROJECT_NAME="hello_blog1"
IMAGE_NAME="$PROJECT_NAME:latest"
CONTAINER_NAME="$PROJECT_NAME"
REMOTE_DEPLOY_PATH="/opt/$PROJECT_NAME"

# 加载 Docker 镜像
echo "Loading Docker image..."
docker load -i $REMOTE_DEPLOY_PATH/$PROJECT_NAME.tar.gz

# 停止并删除现有容器（如果存在）
if [ $(docker ps -aq -f name=$CONTAINER_NAME) ]; then
    echo "Stopping and removing existing container..."
    docker stop $CONTAINER_NAME
    docker rm $CONTAINER_NAME
fi

# 运行新容器
echo "Running new container..."
docker run -d --name $CONTAINER_NAME -p 8080:8080 $IMAGE_NAME

echo "Deployment completed successfully!"
EOF

scp -i $SSH_KEY_PATH -o StrictHostKeyChecking=no remote_deploy.sh $REMOTE_USER@$REMOTE_SERVER:$REMOTE_DEPLOY_PATH/

# 在远程服务器上执行部署脚本
echo "Executing deployment script on remote server..."
ssh -i $SSH_KEY_PATH -o StrictHostKeyChecking=no $REMOTE_USER@$REMOTE_SERVER "chmod +x $REMOTE_DEPLOY_PATH/remote_deploy.sh && $REMOTE_DEPLOY_PATH/remote_deploy.sh"

# 清理本地文件
echo "Cleaning up local files..."
rm -f $PROJECT_NAME.tar.gz remote_deploy.sh

echo "Deployment completed successfully!"